#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include<iostream>
#include<string>
#include <pthread.h>
#include"Mutex.hpp"
using namespace MutexMudole;
//pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
int ticket = 100;
class ThreadData{
    public:
    std::string name;
    Mutex *lockp;
    ThreadData(const std::string& name,Mutex &lockp):name(name),lockp(&lockp) {}
};
void *route(void *arg)
{
	ThreadData *td=(ThreadData*)arg;
	while ( 1 ) {
		td->lockp->Lock();
		if ( ticket > 0 ) {
			usleep(1000);
			printf("%s sells ticket:%d\n", td->name.c_str(), ticket);
			ticket--;
            td->lockp->UnLock();
		} else {
            td->lockp->UnLock();
			break;
		}
	}
}
int main( void )
{
	Mutex lock;
	pthread_t t1, t2, t3, t4;
    ThreadData *td1=new ThreadData("thread 1",lock);
    ThreadData *td2=new ThreadData("thread 2",lock);
    ThreadData *td3=new ThreadData("thread 3",lock);
    ThreadData *td4=new ThreadData("thread 4",lock);
	pthread_create(&t1, NULL, route, (void*)td1);
	pthread_create(&t2, NULL, route, (void*)td2);
	pthread_create(&t3, NULL, route, (void*)td3);
	pthread_create(&t4, NULL, route, (void*)td4);
	pthread_join(t1, NULL);
	pthread_join(t2, NULL);
	pthread_join(t3, NULL);
	pthread_join(t4, NULL);
    return 0;
} 
